<template>
	<n-layout has-sider position="absolute">
    <n-layout-sider bordered
			collapse-mode="width"
			show-trigger="arrow-circle"
			content-style="padding: 24px;"
			:collapsed-width="120"
      :width="240">
			<n-skeleton v-if="loading" height="200px" width="100%" />
      <n-upload
				v-else
				:file-list="fileList"
				list-type="image-card"
				:custom-request="customRequest"
				:max="1"
				@change="handleChange"
				@remove="handleRemove"
			>
				上传图像
			</n-upload>
			<n-input v-model:value="cardName" style="text-align: center;" placeholder="名字" />
			<n-Flex vertical>
				<n-button type="info" @click="addTextarea">新增文本框</n-button>
				<n-button type="primary" :loading="loading" @click="submitText">提交</n-button>
			</n-Flex>
    </n-layout-sider>
    <n-layout>
      <n-layout-content content-style="padding: 24px;" :native-scrollbar="false">
				<n-input
					v-for="item in textareaList"
					:key="item.id"
					style="--header-height: 80px"
					:autosize="{
						minRows: 3,
					}"
					@keydown="textareaTab($event, item)"
					v-model:value="item.content"
					type="textarea"
					placeholder="自动调整尺寸"
					clearable 
				/>
      </n-layout-content>
    </n-layout>
  </n-layout>
</template>
<script setup lang="ts">
	import { inject, reactive, ref, onMounted } from 'vue'
	import { v4 as uuid } from 'uuid'

	import { NUpload, NLayout, NLayoutSider, NLayoutContent, NInput, NButton, NFlex, NSkeleton } from 'naive-ui'
	import { FlashOutline } from '@vicons/ionicons5'

	import { addCard, updateCard, getCard } from '@/api/card'
	import { uploadImage } from '@/api/common'

	const cardId = inject('cardId')
	const type = inject('type')

	// const uploadUrl = import.meta.env.MODE === 'production' ? "http://192.168.1.9:9000/common/image" : '/api/common/image' // 上传的图片服务器地址

  // const baseImage = 'http://localhost:9000'
  const baseImage = 'http://120.79.73.210:9000'
	// 图片
	const fileList = ref([])
	// 文本框
	const textareaList = reactive([{
		id: uuid(),
		content: ''
	}])
	// 卡片名字
	const cardName = ref('')
	// 按钮加载状态
	const loading = ref(false)

	/** tab */
	const textareaTab = (e, item) => {
		if (e.keyCode === 9) {
			if (!item.content) item.content = ''
			item.content += '\t'
			// 阻止默认切换元素的行为
			if (e && e.preventDefault) {
				e.preventDefault()
			} else {
				window.event.returnValue = false
			}
		}
	}

	/** 上传图片改变 */
	const handleChange = (options) => {
		console.log('s')
		if (!options.file.url) {
			if (options.file.status === 'pending') {
				fileList.value.push(options.file)
			} else {
				fileList.value = fileList.value.map(item => {
					if (item.id === options.file.id) {
						item.status = options.file.status
					}
					return item
				})
			}
		}
	}
	/** 删除图片 */
	const handleRemove = (options) => {
		fileList.value = fileList.value.filter(item => item.id !== options.file.id)
	}

	/** 自定义上传 */
	const customRequest = (options) => {
		const formData = new FormData()
		formData.append('file', options.file.file)
		uploadImage(formData).then(res => {
			fileList.value = fileList.value.map(item => {
				if (item.id === options.file.id) {
					item.url = baseImage + res
				}
				return item
			})
			options.onFinish()
		}).catch(err => {
			options.onError()
		})
	}

	/** 新增文本框 */
	const addTextarea = () => {
		textareaList.push({
			id: uuid(),
			content: ''
		})
	}

	/** 获取详情 */
	const getDetail = (cardId) => {
		getCard(cardId).then(res => {
			if (res.img[0]) {
				fileList.value = [{
					id: uuid(),
					name: res.img[0].slice(res.img[0].lastIndexOf('/')+1),
					status: 'finished',
					url: baseImage + res.img[0],
				}]
			}
			cardName.value = res.name
			textareaList.splice(0, 1, ...res.textareaList)
			loading.value = false
		})
	}

	/** 重置 */
	const reset = () => {
		textareaList.splice(0, textareaList.length)
		textareaList.push({
			id: uuid(),
			content: ''
		})
		fileList.value = []
		cardName.value = ''
	}

	const formatUrl = (list) => {
		return list.map(item => item.replace(baseImage, ''))
	}

	/** 提交所有文本和图片 */
	const submitText = () => {
		loading.value = true
		let arr = textareaList.filter(item => {
			return item.content !== ''
		})
		arr.length === 0 ? arr.push({
			id: uuid(),
			content: ''
		}) : arr
		const imgList = formatUrl(fileList.value.map(item => item.url)).join(',')
		if (type.value === 'add') {
			addCard({
				textareaList: JSON.stringify(arr),
				img: imgList,
				name: cardName.value,
			}).then(res => {
				getDetail(res.id)
			})
		} else {
			updateCard({
				id: cardId.value,
				textareaList: JSON.stringify(arr),
				img: imgList,
				name: cardName.value,
			}).then(res => {
				getDetail(cardId.value)
			})
		}
		reset()
	}

	onMounted(() => {
		if (type.value === 'edit') {
			getDetail(cardId.value)
		}
	})

</script>
<style scoped lang="scss">
	::v-deep(.n-upload) {
		width: 100%;
		.n-upload-file-list {
			&.n-upload-file-list--grid {
				grid-template-columns: auto;
			}
			.n-upload-file.n-upload-file--image-card-type {
				width: 100%;
				height: auto;
			}
			.n-upload-trigger.n-upload-trigger--image-card {
				width: 100%;
			}
		}
	}
	.n-input {
		text-align: left;
		color: #fff !important;
		background-color: transparent;
		&:nth-of-type(n + 1) {
			margin-top: 10px;
		}
		::v-deep(.n-input__input-el),
		::v-deep(.n-input__textarea-el) {
			color: #fff;
			&:focus {
				color: var(--n-text-color);
			}
		}
	}
	.n-button {
		margin-top: 20px;
	}
	.n-layout-sider {
		background: url(/src/assets/edit-cat.png) no-repeat bottom center;
    background-size: 100%;
		background-color: transparent;
	}
	.n-layout {
		background-color: transparent;
	}
</style>
  